<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">  
            <a-col :md="48" :sm="48">
              <span class="table-page-search-submitButtons" :style="{ float: 'left', overflow: 'hidden' }">
                <a-button type="primary" @click="handleAdd()">新增</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data="loadData"
        :rowSelection="rowSelection"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
        <span slot="supports" slot-scope="record">
          {{getSupportsTest(record)}}
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)">修改</a>
            <a-divider type="vertical" />
            <a @click="handleDel(record)">删除</a>
          </template>
        </span>
      </s-table>

      <addModal
        ref="addModal"
        :visible="addVisible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleAddOk"
      />
      <editModal
        ref="editModal"
        :visible="editVisible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleEditOk"
      />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { getTagNameList, updateTagName, delTagName, addTagName } from '@/api/platform'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import addModal from './modules/addModal'
import editModal from './modules/editModal'
import { defineComponent } from 'vue';
// import { createVNode, defineComponent } from 'vue';
import { Modal } from 'ant-design-vue';

const columns = [
  {
    title: '序号',
    dataIndex: 'serialNumber'
  },
  {
    title: '平台',
    dataIndex: 'name'
  },
  {
    title: '产物类型',
    dataIndex: 'supports',
    scopedSlots: { customRender: 'supports' }
  },
  {
    title: '平台标识',
    dataIndex: 'tagSystem'
  },
  {
    title: '创建时间',
    dataIndex: 'creationTime',
    sorter: true
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]

const statusMap = {
  0: {
    status: 'default',
    text: '关闭'
  },
  1: {
    status: 'processing',
    text: '运行中'
  },
  2: {
    status: 'success',
    text: '已上线'
  },
  3: {
    status: 'error',
    text: '异常'
  }
}

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    addModal,
    editModal,
  },
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getTagNameList(requestParameters)
          .then(res => {
            return res.data
          })
      },
      selectedRowKeys: [],
      selectedRows: [],

      addVisible:false,
      editVisible:false,
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  created () {
    this.getTagNameList()
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    getSupportsTest(e){
      if(!e || !e.length) return '-'
      let text = ''
      let arr = JSON.parse(e)
      for (let i = 0; i < arr.length; i++) {
        text += `${arr[i]}`
        if(i < arr.length-1){
          text += '、'
        }
      }
      return text
    },
    getTagNameList(){

    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      // this.$refs.modal.visible = true
      this.editVisible = true
      this.mdl = { ...record }
    },
    handleEditOk(){
      const form = this.$refs.editModal.form
      this.confirmLoading = true
      let _self = this
      if(!form.name){
        this.$message.error(`请输入平台`)
        this.confirmLoading = false
        return
      }
      if(!form.tagSystem){
        this.$message.error(`请输入平台标识`)
        this.confirmLoading = false
        return
      }
      if(!form.supports || !form.supports.length){
        this.$message.error(`请选择产物类型`)
        this.confirmLoading = false
        return
      }
      // form.validateFields((errors, values) => {
      //   if (!errors) {
      //     console.log('%c [  ]-194', 'font-size:13px; background:pink; color:#bf2c9f;', values)
          updateTagName(form).then((res)=>{
            const {status,msg} = res.data
            if(status == 200){
              _self.$message.success(`修改成功`)
              _self.editVisible = false
              // 刷新表格
              _self.$refs.table.refresh()
            }else{
              _self.$message.error(msg)
            }
            _self.confirmLoading = false
          })
            _self.confirmLoading = false
        // } else {
        //   this.confirmLoading = false
        // }
      // })
    },
    handleAdd(){
      this.addVisible = true
    },
    handleAddOk(){
      const form = this.$refs.addModal.form
      this.confirmLoading = true
      let _self = this
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('%c [  ]-194', 'font-size:13px; background:pink; color:#bf2c9f;', values)
          addTagName(values).then((res)=>{
            const {status,msg} = res.data
            if(status == 200){
              _self.$message.success(`新增成功`)
              _self.addVisible = false
              // 重置表单数据
              form.resetFields()
              _self.$refs.table.refresh()
            }else{
              _self.$message.error(msg)
            }
            // 刷新表格
            _self.confirmLoading = false
          })
          _self.confirmLoading = false
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          if (values.id > 0) {
            // 修改 e.g.
            new Promise((resolve, reject) => {
              setTimeout(() => {
                resolve()
              }, 1000)
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('修改成功')
            })
          } else {
            // 新增
            new Promise((resolve, reject) => {
              setTimeout(() => {
                resolve()
              }, 1000)
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('新增成功')
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.addVisible = false
      this.editVisible = false
       // 清理表单数据
      // const form1 = this.$refs.editModal.form
      const form2 = this.$refs.addModal.form
      // form1.resetFields()
      form2.resetFields() 
    },
    handleDel (record) {
      let _self = this
      this.confirmLoading = true
      Modal.confirm({
        title: `确定删除${record.name}吗`,
        // icon: createVNode(ExclamationCircleOutlined),
        // content: createVNode('div', { style: 'color:red;' }, 'Some descriptions'),
        onOk() {
          console.log('OK');
          delTagName({id:record.id}).then((res)=>{
            console.log('%c [ res ]-336', 'font-size:13px; background:pink; color:#bf2c9f;', res)
            if(res.status == 200){
              _self.$message.success(`删除成功`)
              _self.editVisible = false
              _self.$refs.table.refresh()
            }else{
              _self.$message.error(res.msg)
            }
          })
          _self.confirmLoading = false
        },
        onCancel() {
          console.log('Cancel');
          _self.confirmLoading = false
        },
        class: 'test',
      });

      // if (record.status !== 0) {
      //   this.$message.info(`${record.no} 订阅成功`)
      // } else {
      //   this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      // }
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        "name": "",
        "page": 0,
        "pageNum": 1,
        "pageSize": 10,
        "tagSystem": ""
      }
    }
  }
}
</script>
